package com.ruoyi.web.controller.system;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;

/**
 * 货物参数Controller
 * 
 * @author ruoyi
 * @date 2020-12-13
 */
@Controller
@RequestMapping("/system/goodparameter")
public class SysGoodparameterController extends BaseController
{
    private String prefix = "system/goodparameter";

    @Autowired
    private ISysGoodparameterService sysGoodparameterService;
    @Autowired
    private ISysSuppliergoodsimplowerService sysSuppliergoodsimplowerService;
    @Autowired
    private ISysGoodsService sysGoodsService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysPeixuanjianService sysPeixuanjianService;

    @RequiresPermissions("system:goodparameter:view")
    @GetMapping()
    public String goodparameter()
    {
        return prefix + "/goodparameter";
    }

/*    *//**
     * 货物审核
     * @return
     *//*
    @RequiresPermissions("system:goodparameter:view2")
    @GetMapping()
    public String shenhe()
    {
        return prefix + "/goodparameterShenHe";
    }*/
    /**
     * 查询货物参数列表
     */
    @RequiresPermissions("system:goodparameter:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysGoodparameter sysGoodparameter)
    {

        Long unitId = ShiroUtils.getUserId();
        SysUser sysUser=userService.selectUserById(unitId);
        List<SysGoodparameter> list = new ArrayList<SysGoodparameter>();
        if(sysUser.getUserType().equals("11")){
            sysGoodparameter.setSupplierId(sysUser.getCompanyId());
            startPage();
           list = sysGoodparameterService.selectSysGoodparameterList(sysGoodparameter);
        }else{
            startPage();
            list = sysGoodparameterService.selectSysGoodparameterList(sysGoodparameter);
        }
        return getDataTable(list);
    }

    /**
     * 导出货物参数列表
     */
    @RequiresPermissions("system:goodparameter:export")
    @Log(title = "货物参数", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysGoodparameter sysGoodparameter)
    {

        List<SysGoodparameter> list = sysGoodparameterService.selectSysGoodparameterList(sysGoodparameter);
        ExcelUtil<SysGoodparameter> util = new ExcelUtil<SysGoodparameter>(SysGoodparameter.class);
        return util.exportExcel(list, "goodparameter");
    }

    /**
     * 新增货物参数
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        SysUser sysUser=ShiroUtils.getSysUser();
        SysSuppliergoodsimplower sysSuppliergoodsimplower=new SysSuppliergoodsimplower();
        sysSuppliergoodsimplower.setSupplierId(sysUser.getCompanyId());
        List<GrantType> goodsTypes=sysSuppliergoodsimplowerService.selectGrantTypeList(sysSuppliergoodsimplower);
        mmap.put("goodsTypes",goodsTypes);
        if(goodsTypes!=null &&goodsTypes.size()>0){
            if(goodsTypes.get(0).getSmallList()!=null && goodsTypes.get(0).getSmallList().size()>0){
                SysGoods sysGoods=new SysGoods();
                sysGoods.setGoodsClassificationId(Long.parseLong(goodsTypes.get(0).getSmallList().get(0).getBigGoodsType()));
                List<SysGoods> goods=sysGoodsService.selectSysGoodsList(sysGoods);
                mmap.put("goods",goods);
            }

        }
        return prefix + "/add";
    }

    /**
     * 新增保存货物参数
     */
    @RequiresPermissions("system:goodparameter:add")
    @Log(title = "货物参数", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SysGoodparameter sysGoodparameter,String goodParameters, HttpServletRequest request)
    {
        Long unitId = ShiroUtils.getUserId();
        SysUser sysUser=ShiroUtils.getSysUser();
        sysGoodparameter.setSupplierId(sysUser.getCompanyId());
        sysGoodparameter.setGoodStatus("0");
//        Session session = ShiroUtils.getSession();
//        Map<String, String> path = (Map<String, String>) session.getAttribute("uploadImage");
//        if(path!=null){
//            Set<String> pathSet=path.keySet();
//            String[] arr = pathSet.toArray(new String[pathSet.size()]);
//            String arrs=JSONArray.toJSONString(arr);
//            sysGoodparameter.setImageUrl(arrs);
//        }
        int row=sysGoodparameterService.insertSysGoodparameter(sysGoodparameter);
        String withOption=sysGoodparameter.getWithoption();
        List<Para> paras=JSONArray.parseArray(withOption,Para.class);
        for(Para para:paras){
            SysPeixuanjian sysPeixuanjian=new SysPeixuanjian();
            sysPeixuanjian.setGoodParameterId(sysGoodparameter.getGoodParameterId()+"");
            sysPeixuanjian.setGoodName(para.getOptionsName());
            sysPeixuanjian.setAttribite1(para.getVariablePrice());
            sysPeixuanjian.setCreateTime(new Date());
            sysPeixuanjianService.insertSysPeixuanjian(sysPeixuanjian);
        }
        return toAjax(row);
    }

    /**
     * 修改货物参数
     */
    @GetMapping("/edit/{goodParameterId}")
    public String edit(@PathVariable("goodParameterId") Long goodParameterId, ModelMap mmap)
    {
        SysUser sysUser=ShiroUtils.getSysUser();
        SysSuppliergoodsimplower sysSuppliergoodsimplower=new SysSuppliergoodsimplower();
        sysSuppliergoodsimplower.setSupplierId(sysUser.getCompanyId());
        List<GrantType> goodsTypes=sysSuppliergoodsimplowerService.selectGrantTypeList(sysSuppliergoodsimplower);
        mmap.put("goodsTypes",goodsTypes);
        SysGoodparameter sysGoodparameter = sysGoodparameterService.selectSysGoodparameterById(goodParameterId);
        mmap.put("sysGoodparameter", sysGoodparameter);
        return prefix + "/edit";
    }
    /**
     * 修改货物参数
     */
    @GetMapping("/editread/{goodParameterId}")
    public String editread(@PathVariable("goodParameterId") Long goodParameterId, ModelMap mmap)
    {
        SysUser sysUser=ShiroUtils.getSysUser();
        SysSuppliergoodsimplower sysSuppliergoodsimplower=new SysSuppliergoodsimplower();
        sysSuppliergoodsimplower.setSupplierId(sysUser.getCompanyId());
        List<GrantType> goodsTypes=sysSuppliergoodsimplowerService.selectGrantTypeList(sysSuppliergoodsimplower);
        mmap.put("goodsTypes",goodsTypes);
        SysGoodparameter sysGoodparameter = sysGoodparameterService.selectSysGoodparameterById(goodParameterId);
        mmap.put("sysGoodparameter", sysGoodparameter);
        return prefix + "/editreadonly";
    }

    /**
     * 修改货物参数
     */
    @GetMapping("/look/{goodParameterId}")
    public String look(@PathVariable("goodParameterId") Long goodParameterId, ModelMap mmap)
    {
        SysUser sysUser=ShiroUtils.getSysUser();
        SysSuppliergoodsimplower sysSuppliergoodsimplower=new SysSuppliergoodsimplower();
        sysSuppliergoodsimplower.setSupplierId(sysUser.getCompanyId());
        List<GrantType> goodsTypes=sysSuppliergoodsimplowerService.selectGrantTypeList(sysSuppliergoodsimplower);
        mmap.put("goodsTypes",goodsTypes);
        SysGoodparameter sysGoodparameter = sysGoodparameterService.selectSysGoodparameterById(goodParameterId);
        mmap.put("sysGoodparameter", sysGoodparameter);
        return prefix + "/look";
    }
    /**
     * 修改保存货物参数
     */
    @RequiresPermissions("system:goodparameter:edit")
    @Log(title = "货物参数", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SysGoodparameter sysGoodparameter)
    {
        String withOption=sysGoodparameter.getWithoption();

        List<Para> paras=JSONArray.parseArray(withOption,Para.class);
        for(Para para:paras){
            SysPeixuanjian sysPeixuanjian=new SysPeixuanjian();
            sysPeixuanjian.setGoodParameterId(sysGoodparameter.getGoodParameterId()+"");
            sysPeixuanjian.setGoodName(para.getOptionsName());
            sysPeixuanjian.setAttribite1(para.getVariablePrice());
            sysPeixuanjian.setCreateTime(new Date());
            if(para.getId()!=null){
                sysPeixuanjian.setPeiXuanJianId(para.getId());
                sysPeixuanjianService.updateSysPeixuanjian(sysPeixuanjian);
            }else{
                sysPeixuanjianService.insertSysPeixuanjian(sysPeixuanjian);
            }
        }
        return toAjax(sysGoodparameterService.updateSysGoodparameter(sysGoodparameter));
    }

    /**
     * 删除货物参数
     */
    @RequiresPermissions("system:goodparameter:remove")
    @Log(title = "货物参数", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(sysGoodparameterService.deleteSysGoodparameterByIds(ids));
    }


    public String unescape(String src) {
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length());
        int lastPos = 0, pos = 0;
        char ch;
        while (lastPos < src.length()) {
            pos = src.indexOf("%", lastPos);
            if (pos == lastPos) {
                if (src.charAt(pos + 1) == 'u') {
                    ch = (char) Integer.parseInt(src
                            .substring(pos + 2, pos + 6), 16);
                    tmp.append(ch);
                    lastPos = pos + 6;
                } else {
                    ch = (char) Integer.parseInt(src
                            .substring(pos + 1, pos + 3), 16);
                    tmp.append(ch);
                    lastPos = pos + 3;
                }
            } else {
                if (pos == -1) {
                    tmp.append(src.substring(lastPos));
                    lastPos = src.length();
                } else {
                    tmp.append(src.substring(lastPos, pos));
                    lastPos = pos;
                }
            }
        }
        return tmp.toString();
    }
    }
